package com.winit.openapi.rma.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.rma.RMAOrderClaimTagService;
import com.winit.oms.spi.rma.RMAOrderMerchandiseService;
import com.winit.oms.spi.rma.RMAOrderService;
import com.winit.oms.spi.rma.command.CancelRMAOrderCommand;
import com.winit.oms.spi.rma.command.QueryClaimTagCommand;
import com.winit.oms.spi.rma.command.RMAOrderCommand;
import com.winit.oms.spi.rma.command.RMAOrderMerchandiseCommand;
import com.winit.oms.spi.rma.command.SubmitRMAOrderCommand;
import com.winit.oms.spi.rma.command.UpdateRMAOrderCommand;
import com.winit.oms.spi.rma.vo.RMAClaimTagVo;
import com.winit.oms.spi.rma.vo.RMAEnumConstant;
import com.winit.oms.spi.rma.vo.RMAOrderMerchandiseVo;
import com.winit.oms.spi.rma.vo.RMAOrderVo;
import com.winit.oms.spi.rma.vo.ValidateRMAOrderVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.rma.builder.RmaOrderBuilder;
import com.winit.openapi.rma.validator.RmaOrderValidator;
import com.winit.openapi.util.ValidateUtil;

/**
 * 退货单
 * 
 * @version <pre>
 * Author	  Version		Date		Changes
 * dinghua.an	1.0  		2016年3月7日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/rma/returnGoodsOrder")
public class RmaOrderController extends BaseController {

    @Resource
    private RMAOrderService            returnOrderService;

    @Resource
    private RMAOrderClaimTagService    rMAOrderClaimTagService;

    @Resource
    private RMAOrderMerchandiseService rmaOrderMerchandiseService;

    /**
     * eaby 同步下单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/create")
    public String create(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            RmaOrderValidator.validBaseField(json);
            command.setReturnOrderVo(RmaOrderBuilder.buildRMAOrder(json));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        String returnOrderNo = returnOrderService.create(command);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("returnGoodsOrderNo", returnOrderNo);
        responseMsg.setData(resultMap);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 新增退货单第一步
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/firstStep")
    public String firstStep(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            RmaOrderValidator.validBaseField(json);
            command.setReturnOrderVo(RmaOrderBuilder.buildRMAOrder(json));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        String returnOrderNo = returnOrderService.firstStep(command);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("returnGoodsOrderNo", returnOrderNo);
        responseMsg.setData(resultMap);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 新增退货单第二步
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/secondStep")
    public String secondStep(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            RmaOrderValidator.validSecondField(json);
            command.setReturnOrderVo(RmaOrderBuilder.buildMerchandise(json));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        String returnOrderNo = returnOrderService.secondStep(command);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("returnGoodsOrderNo", returnOrderNo);
        responseMsg.setData(resultMap);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 提交退货单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/submit")
    public String submit(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        SubmitRMAOrderCommand command = new SubmitRMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 退货单号
            ValidateUtil.validMaxLength(json, "returnGoodsOrderNo", 64, true);
            command.setReturnGoodsOrderNo(json.getString("returnGoodsOrderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        returnOrderService.submitReturnOrder(command);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 查询退货单列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = RmaOrderBuilder.buildSearchOrderCommand(json);
            Searchable searchable = buildSearchablePageParams(json);
            searchable.addSort(new Sort(Direction.DESC, "CREATED"));
            command.setSearchable(searchable);
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            Searchable searchable = buildSearchablePageParams(null);
            command = new RMAOrderCommand();
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());

        Page<RMAOrderVo> pList = returnOrderService.getReturnOrderList(command);
        // 调用接口分页查询订单
        if (pList != null) {
            List<Map<String, Object>> datalist = RmaOrderBuilder.buildOrderList(pList.getContent());
            Map<String, Object> pageMap = getPageParams(pList);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", datalist);
            data.put("pageParams", pageMap.get("pageParams"));
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 查询退货单详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getOrderDetails")
    public String getOrderDetails(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 退货单号
            ValidateUtil.validMaxLength(json, "returnGoodsOrderNo", 64, true);
            command.setRmaOrderNo(json.getString("returnGoodsOrderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        RMAOrderVo vo = returnOrderService.getReturnOrderDetails(command);
        if (vo != null) {
            responseMsg.setData(RmaOrderBuilder.buildOrderDetails(vo));
        }
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 查询退货单详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getOrderDetailsAndItemSero")
    public String getOrderDetailsAndItemSero(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 退货单号
            ValidateUtil.validMaxLength(json, "returnGoodsOrderNo", 64, true);
            command.setRmaOrderNo(json.getString("returnGoodsOrderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        RMAOrderVo vo = returnOrderService.getReturnOrderDetails(command);
        if (vo != null) {
            responseMsg.setData(RmaOrderBuilder.buildOrderDetailsAnItemSerno(vo));
        }
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 取消退货单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/cancel")
    public String cancel(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        CancelRMAOrderCommand command = new CancelRMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 退货单号
            ValidateUtil.validMaxLength(json, "returnGoodsOrderNo", 64, true);
            command.setReturnGoodsOrderNo(json.getString("returnGoodsOrderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        returnOrderService.cancelReturnOrder(command);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 查询待办事项
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/todoList")
    public String getTodoList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        QueryClaimTagCommand command = null;
        if (obj instanceof JSONObject) {
            command = new QueryClaimTagCommand();
            JSONObject json = (JSONObject) obj;
            Searchable<?> searchable = buildSearchablePageParams(json);
            command.setSearchable(searchable);
            searchable.addSort(new Sort(Direction.DESC, "CREATED"));
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            command = new QueryClaimTagCommand();
            Searchable<?> searchable = buildSearchablePageParams(null);
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());
        Page<RMAClaimTagVo> rMAClaimTagVoList = rMAOrderClaimTagService.queryClaimTagList(command);
        // 调用接口分页查询订单
        if (rMAClaimTagVoList != null) {
            List<Map<String, Object>> datalist = RmaOrderBuilder.buildTodaoList(rMAClaimTagVoList.getContent());
            Map<String, Object> pageMap = getPageParams(rMAClaimTagVoList);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("todoList", datalist);
            data.put("pageParams", pageMap.get("pageParams"));
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 更新退货单商品标记
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateMerchandise")
    public String updateMerchandise(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderMerchandiseCommand command = new RMAOrderMerchandiseCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            RmaOrderValidator.validMerchdise(json);
            RMAOrderMerchandiseVo merchandiseVo = new RMAOrderMerchandiseVo();
            RmaOrderBuilder.buildBaseMerchandise(json, merchandiseVo);
            if (StringUtils.isEmpty(merchandiseVo.getMerchandiseSerno())) {
                merchandiseVo.setMerchandiseSerno(merchandiseVo.getOriginalMerchandiseSerno());
            }
            merchandiseVo.setIsComplete("Y");
            merchandiseVo.setReturnOrderNo(json.getString("returnGoodsOrderNo"));
            command.setMerchandiseVo(merchandiseVo);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        rmaOrderMerchandiseService.updateMerchandise(command);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 根据退货单号查询商品信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getRmaOrderMerchandiseList")
    public String getRmaOrderMerchandiseList(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.isNotNull(json, "returnGoodsOrderNo");
            command.setRmaOrderNo(json.getString("returnGoodsOrderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        List<RMAOrderMerchandiseVo> merList = rmaOrderMerchandiseService.getRmaOrderMerchandiseList(command);
        if (null != merList && merList.size() > 0) {
            responseMsg.setData(RmaOrderBuilder.buildMerchandise(merList));
        }
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 新增订单备注
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateOrderDesc")
    public String updateOrderDesc(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        UpdateRMAOrderCommand command = new UpdateRMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validMaxLength(json, "orderDesc", 255);
            ValidateUtil.isNotNull(json, "returnGoodsOrderNo");
            ValidateUtil.validMaxLength(json, "returnGoodsOrderNo", 64, true);
            command.setReturnGoodsOrderNo(json.getString("returnGoodsOrderNo"));
            command.setOrderDesc(json.getString("orderDesc"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        returnOrderService.updateOrderDesc(command);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 查询退货单列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/exportReturnORder")
    public String exportReturnORder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = RmaOrderBuilder.buildSearchOrderCommand(json);
        } else if (obj == null || StringUtils.isBlank(obj.toString())) {
            command = new RMAOrderCommand();
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        command.setCtx(CommandContext.getContext());

        List<RMAOrderVo> pList = returnOrderService.exportReturnORder(command);
        if (pList != null && pList.size() > 0) {
            List<RMAOrderVo> orderList = new ArrayList<RMAOrderVo>();
            for (RMAOrderVo vo : pList) {
                if (!RMAEnumConstant.OrderStatus.VO.getStatus().equals(vo.getStatus())) {
                    orderList.add(vo);
                }
            }
            responseMsg.setData(RmaOrderBuilder.buildExportReturnOrder(orderList));
        }
        
        return SUCCESS;
    }

    @RequestMapping(value = "/validateReturnOrder")
    public String validateReturnOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.isNotNull(json, "returnOrderNo");
            command.setRmaOrderNo(json.getString("returnOrderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        ValidateRMAOrderVo rmaOrderVo = returnOrderService.validateReturnOrder(command);
        if ("N".equals(rmaOrderVo.getIsStartDestroy())) {
            throw new ApiException(ErrorCode.RETURN_MERCHANDISE_ALREADY_MAINTAIN);
        }
        if (StringUtils.isNotBlank(rmaOrderVo.getRmaOrderNos())) {
            throw new ApiException(ErrorCode.RETURN_ORDER_DESTROY, rmaOrderVo.getRmaOrderNos());
        }
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 更新退货单快递单号
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateReturnOrderExpressNo")
    public String updateReturnOrderExpressNo(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validMaxLength(json, "returnOrderNo", 64, true);
            ValidateUtil.validMaxLength(json, "expressNo", 125, true);
            RMAOrderVo returnOrderVo = new RMAOrderVo();
            returnOrderVo.setRmaOrderNo(json.getString("returnOrderNo").trim());
            returnOrderVo.setCustomerExpressNo(json.getString("expressNo").trim());
            command.setReturnOrderVo(returnOrderVo);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        returnOrderService.updateRmaOrderExpressNo(command);
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }

    /**
     * 查询退货单处理状态
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getReturnOrderHandleStatus")
    public String getReturnOrderHandleStatus(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        RMAOrderCommand command = new RMAOrderCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 退货单号
            ValidateUtil.validMaxLength(json, "returnOrderNo", 64, true);
            command.setRmaOrderNo(json.getString("returnOrderNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        RMAOrderVo vo = returnOrderService.getReturnOrderByNo(command);
        if (vo != null) {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("updateExpressNoDate", vo.getUpdateExpressNoDate());
            data.put("expressNo", vo.getCustomerExpressNo());
            data.put("handleStatus", vo.getHandleStatus());
            responseMsg.setData(data);
        }
        responseMsg.setMsg("SUCCESS");
        return SUCCESS;
    }
}
